<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use App\Models\UserRequirement;
use Carbon\Carbon;
use \Cache;
use \Auth;
use \Schema;

class UserRequirementController extends Controller
{
    protected $ignoreParameters = ['created_at', 'updated_at', 'user_id'];

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     * @throws \Illuminate\Validation\ValidationException
     */
    public function set(Request $request)
    {
        $this->validate($request,[
            'lowest_age'=>'nullable|numeric',
            'highest_age'=>'nullable|numeric',
            'height'=>'nullable|numeric',
            'income'=>'nullable|string',
            'education'=>'nullable|string',
            'if_married'=>'nullable|numeric',
            'shape'=>'nullable|string',
            'province'=>'nullable|string',
            'city'=>'nullable|string',
            'county'=>'nullable|string',
            'if_child'=>'nullable|numeric',
            'if_want_child'=>'nullable|numeric',
            'smoke'=>'nullable|numeric',
            'drink'=>'nullable|numeric',
        ]);
        $inputs = $request->input();
        $user = User::where('id',Auth::user()->id)->first();
        if( empty($user) )
        {
            return response('用户不存在', 403);
        }
        $userRequirement = UserRequirement::firstOrCreate(['user_id' => Auth::user()->id]);
        $filters = Schema::getColumnListing('user_requirements');
        $ignores = $this->ignoreParameters;
        $infoParams = array_filter($inputs, function ($key) use ($filters, $ignores) {
            return in_array($key, $filters) && !in_array($key, $ignores);
        }, ARRAY_FILTER_USE_KEY);
        $result = UserRequirement::where(['user_id' => Auth::user()->id])->update($infoParams);
        return $this->successReturn($result);
    }


    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function show()
    {
        $user_requirement = UserRequirement::where(['user_id' => Auth::user()->id])->first();
        return $this->successReturn($user_requirement);
    }
}